package com.sanjin.mall.product.service.impl;

import com.sanjin.mall.product.entity.AttrEntity;
import com.sanjin.mall.product.service.AttrService;
import com.sanjin.mall.product.vo.AttrAndGroupRespVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sanjin.mall.common.utils.PageUtils;
import com.sanjin.mall.common.utils.Query;

import com.sanjin.mall.product.dao.AttrGroupDao;
import com.sanjin.mall.product.entity.AttrGroupEntity;
import com.sanjin.mall.product.service.AttrGroupService;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    @Lazy
    AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    //用于带参数的查询
    @Override
    public PageUtils queryPage(Map<String, Object> params, Integer cateId) {
        if (cateId == 0) {
            return queryPage(params);
        } else {
            String key = (String) params.get("key");
            QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
            // select * from attr_group where cateid = ? and key = ?
            wrapper.eq("catelog_id", cateId);
            if (StringUtils.isNotEmpty(key)) {
                wrapper.and((obj) -> {
                    obj.like("attr_group_name", key).or().eq("attr_group_id", key);
                });
            }
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    wrapper
            );
            return new PageUtils(page);
        }



    }

    @Override
    public List<AttrAndGroupRespVo> getAttrGroupWithAttrsByCatelogId(Long catelogId) {
        List<AttrGroupEntity> groups = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));

        return groups.stream().map(x -> {
            AttrAndGroupRespVo respVo = new AttrAndGroupRespVo();
            BeanUtils.copyProperties(x, respVo);
            List<AttrEntity> attrEntityList = attrService.getRelationAttr(x.getAttrGroupId());
            respVo.setAttrs(attrEntityList);
            return respVo;
        }).collect(Collectors.toList());

    }

}